package com.memer

import org.apache.kafka.clients.producer.{KafkaProducer, ProducerConfig, ProducerRecord}
import org.apache.kafka.common.serialization.StringDeserializer
import org.apache.spark.SparkConf
import org.apache.spark.streaming.kafka010.LocationStrategies.PreferConsistent
import org.apache.spark.streaming.kafka010.{ConsumerStrategies, KafkaUtils}
import org.apache.spark.streaming.{Seconds, StreamingContext}

import java.util.HashMap

object Three {


  def main(args: Array[String]): Unit = {


    val conf = new SparkConf().setMaster("local[*]").setAppName("streamingKafka1")
    val streamingCon = new StreamingContext(conf, Seconds(2))


    val topic =  "library"
    val group = "niit2"

    streamingCon.sparkContext.setLogLevel("error")


    val  kafkaParams = Map[String, Object](
      "bootstrap.servers" -> "123.56.187.176:9092",
      "key.deserializer" -> classOf[StringDeserializer],
      "value.deserializer" -> classOf[StringDeserializer],
      "group.id" -> group,
      "auto.offset.reset" -> "earliest",
      "enable.auto.commit" -> (false: java.lang.Boolean)
    )

    // 记录 元数据  ，消费位置信息
    streamingCon.checkpoint("./checkpoint")

    val topics = Array(topic)

    // 连接 kafka 配置项
    val streamRdd = KafkaUtils.createDirectStream(
      streamingCon,
      PreferConsistent,
      ConsumerStrategies.Subscribe[String, String](topics, kafkaParams)
    )

     val lines = streamRdd.map(_.value())

    //处理逻辑
    lines.foreachRDD(
      x=>{
        val c=x.map(
          line=>{
            val zaiku = line.split("\t")(0)
            val num = line.split("\t")(2)
            val num1 = num.toInt
            (zaiku,num1)
          }
        ).reduceByKey(_+_)
        c.foreach(
          x=>{
            val a=x._1
            val b=x._2
            val str=a+"\t"+b
            println(str)

            val props = new HashMap[String,Object]()
            props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG,"niit01:9092")
            props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringSerializer")
            props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringSerializer")

            val producer = new KafkaProducer[String, String](props)
            val record = new ProducerRecord[String, String]("Second",str)
            producer.send(record)
          }
        )




      }
    )


    //lines.print()




    streamingCon.start()
    streamingCon.awaitTermination()

  }



}
